<!--  -->
<template>
  <div class="userlist">
    <headers></headers>
    <!-- 表格 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="商品名称">
              <span>{{ props.row.name }}</span> </el-form-item
            ><br />
            <el-form-item label="所属店铺">
              <span>{{ props.row.shop }}</span> </el-form-item
            ><br />
            <el-form-item label="商品 ID">
              <span>{{ props.row.id }}</span> </el-form-item
            ><br />
            <el-form-item label="店铺 ID">
              <span>{{ props.row.shopId }}</span> </el-form-item
            ><br />
            <el-form-item label="商品分类">
              <span>{{ props.row.category }}</span> </el-form-item
            ><br />
            <el-form-item label="店铺地址">
              <span>{{ props.row.address }}</span> </el-form-item
            ><br />
            <el-form-item label="商品描述">
              <span>{{ props.row.desc }}</span> </el-form-item
            ><br />
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="名称" prop="name"> </el-table-column>
      <el-table-column label="商品介绍" prop="introduce"> </el-table-column>
      <el-table-column label="评分" prop="score"> </el-table-column>
      <!-- 操作 -->
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="openEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 弹出修改框 -->
    <el-dialog title="修改食品信息" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules">
        <el-form-item
          label="食品名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="食品介绍" :label-width="formLabelWidth">
          <el-input v-model="form.description" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="食品分类" :label-width="formLabelWidth">
          <el-select v-model="form.region" placeholder="热销榜">
            <el-option label="区域一" value="shanghai"></el-option>
            <el-option label="区域二" value="beijing"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="食品图片" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            :action="baseUrl + '/v1/addimg/food'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="showImgpath"
              :src="baseImgPath + showImgpath"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 添加规格 -->
      <el-row style="overflow: auto; text-align: center">
        <el-table :data="specData" style="width: 100%">
          <el-table-column label="规格" prop="specs"> </el-table-column>
          <el-table-column label="包装费" prop="packing_fee"> </el-table-column>
          <el-table-column label="价格" prop="price"> </el-table-column>
          <!-- 操作 -->
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                @click="handleDeleteSpec(scope.$index, scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          @click="specsFormVisible = true"
          style="margin-bottom: 10px"
          >添加规格</el-button
        >
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updatafoods">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加规格弹窗 -->
    <el-dialog title="添加规格" :visible.sync="specsFormVisible">
      <el-form :model="form2" :rules="rules">
        <el-form-item label="规格" :label-width="formLabelWidth" prop="specs">
          <el-input v-model="form2.specs" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="包装费" :label-width="formLabelWidth">
          <el-input-number
            v-model="form2.packing_fee"
            :min="1"
            :max="10"
            label="描述文字"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="价格" :label-width="formLabelWidth">
          <el-input-number
            v-model="form2.price"
            :min="1"
            :max="10000"
            label="描述文字"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="specsFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addpreclist">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分页器 -->
    <div class="pagebox">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagenow"
        layout=" prev, pager, next, jumper"
        :total="counts"
        :page-size="3"
      >
      </el-pagination>
      <el-pagination layout="total" :total="counts"> </el-pagination>
    </div>
  </div>
</template>

<script>
import Header from "./header";
import { getAllfoodcount, getFoodslist, updatafood } from "../axios/api";
import { baseUrl, baseImgPath } from "@/config/env";
export default {
  data() {
    //这里存放数据
    return {
      baseUrl,
      baseImgPath,
      showImgpath: "",
      tableData: [], //食品列表数据
      pagenow: 1, //当前显示页码
      counts: 0, //总食品数量
      dialogFormVisible: false, //修改弹出框显示判断变量
      specsFormVisible: false, //规格弹出框显示判断变量
      // option: [],
      form: {
        name: "名称",
        description: "介绍",
        item_id: 1,
        specfoods: [],

        // region: "",
        // date1: "",
        // date2: "",
        // delivery: false,
        // type: [],
        // resource: "",
        // desc: "",
      }, //修改弹出框的表单数据
      form2: {
        specs: "优惠卷",
        packing_fee: 1,
        price: 20,
      }, //添加规格弹出框的表单数据
      formLabelWidth: "120px",
      imageUrl: "", //图片地址
      specData: [
        {
          specs: "默认",
          packing_fee: 1,
          price: 20,
        },
      ],
      rules: {
        spec: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        name: [
          { required: true, message: "请输入食品名称", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
      },
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //组件
  components: {
    headers: Header,
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    /* 连接接口获取数据 */
    getfoodlist: function () {
      var start = this.pagenow;
      getFoodslist({ offset: (start - 1) * 3, limit: 3 }).then((res) => {
        this.tableData = [];
        res.forEach((item, index) => {
          var tabledata = {};
          tabledata.item_id = item.item_id;
          tabledata.name = item.name;
          tabledata.introduce = item.description;
          tabledata.score = item.rating;
          tabledata.month_sales = item.month_sales;
          tabledata.restaurant_id = item.restaurant_id;
          tabledata.category_id = item.category_id;
          tabledata.image_path = item.image_path;
          tabledata.specfoods = item.specfoods;
          tabledata.index = index;
          this.tableData.push(tabledata);
        });
        // this.option = res;
      });
      getAllfoodcount().then((res) => {
        this.counts = res.count;
      });
    },
    /* 每页数据条数 */
    handleSizeChange(val) {},
    /* 当前页当切换页码时候触发 */

    handleCurrentChange(val) {
      this.pagenow = val;
      this.getfoodlist();
    },
    /* 打开编辑 */
    openEdit(index, row) {
      this.dialogFormVisible = true;
      this.showImgpath = this.tableData[index].image_path;
      this.specData = [];
      /* 更新规格列表数据 */
      this.tableData[index].specfoods.forEach((item, index) => {
        var specArr = {
          specs: item.name,
          packing_fee: item.packing_fee,
          price: item.price,
        };
        this.specData.push(specArr);
      });
      /* 更新form内数据 */
      this.form.name = this.tableData[index].name;
      this.form.description = this.tableData[index].introduce;
      this.form.image_path = this.tableData[index].image_path;
      this.form.restaurant_id = this.tableData[index].restaurant_id;
      this.form.category_id = this.tableData[index].category_id;
      this.form.specfoods = this.specData;
      // console.log(this.tableData);
    },
    /* 删除 */
    handleDelete(index, row) {
      // this.tableData.splice(index, 1);
      console.log(row);
    },
    /* 删除规格 */
    handleDeleteSpec(index, row) {
      this.specData.splice(index, 1);
    },
    /* 图片上传 */
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    /* 添加规格 */
    addpreclist() {
      this.specsFormVisible = false;

      const addData = {
        specs: this.form2.specs,
        packing_fee: this.form2.packing_fee,
        price: this.form2.price,
      };
      this.specData.push(addData);

      // this.specData.push(form2);

      // const addData = form2;
      // this.specData.push(addData);
    },
    /* 更新食物信息 */
    updatafoods() {
      var dataarr = {
        name: this.form.name,
        description: this.form.description,
        image_path: this.form.image_path,
        restaurant_id: this.form.restaurant_id,
        category_id: this.form.category_id,
        specfoods: this.form.specfoods,
      };
      updatafood(dataarr).then((res) => {
        console.log(res);
      });
      console.log(dataarr);
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getfoodlist();
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style  lang='less'>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>